package main

import (
	"os"
	"os/signal"

	"../logger"
	"../util"
	"github.com/valyala/fasthttp"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	basepath = kingpin.Flag("path", "base path").Default(".").String()
	port     = kingpin.Flag("port", "port to listen").Default("10101").Short('p').String()
)

func main() {
	kingpin.Parse()
	logger.SetOutput(*basepath+"/logs/", "crm-post", 3)

	srv := Initialize()
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan)
	go func() {
		a := <-signalChan
		logger.Printf("Receive signal %v\n", a)
		Finalize(&srv)
		os.Exit(0)
	}()
	err := fasthttp.ListenAndServe(":"+*port, srv.Handle)
	util.ErrorHandler("listen to HTTP request", err, func() error {
		return fasthttp.ListenAndServe(":"+*port, srv.Handle)
	})
}

func Initialize() (srv Server) {
	p, err := NewProducer()
	util.ErrorHandler("Open Kafka producer", err, func() error {
		p, err = NewProducer()
		return err
	})
	/*
		if err != nil {
			logger.Errorf("Open Kafka producer error: %v", err)
			os.Exit(2)
		}
	*/
	if p.producer == nil {
		os.Exit(2)
	}
	srv = Server{producer: p}
	return
}

func Finalize(srv *Server) {
	var err error
	err = srv.producer.Close()
	util.ErrorHandler("close Kafka producer", err, func() error {
		return srv.producer.Close()
	})
	logger.Close()
}
